<template>
  <div class="execution-reports-view">
    <div class="toolbar">
      <div class="search-filters">
        <el-select
          v-model="filterStatus"
          placeholder="状态筛选"
          clearable
          size="small"
          style="width: 120px"
          @change="loadExecutions"
        >
          <el-option label="待执行" value="pending" />
          <el-option label="执行中" value="running" />
          <el-option label="成功" value="success" />
          <el-option label="失败" value="failed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>

        <el-select
          v-model="filterType"
          placeholder="执行类型"
          clearable
          size="small"
          style="width: 120px"
          @change="loadExecutions"
        >
          <el-option label="单个执行" value="single" />
          <el-option label="批量执行" value="batch" />
        </el-select>
      </div>
      
      <el-button size="small" @click="loadExecutions">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="executions"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="execution_name" label="执行文件名" width="180" />
      <el-table-column prop="script_name" label="脚本名称" width="150" />
      
      <el-table-column prop="execution_type" label="执行类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.execution_type === 'batch' ? 'warning' : 'info'" size="small">
            {{ row.execution_type === 'batch' ? '批量' : '单个' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="report_file_name" label="报告文件" width="200">
        <template #default="{ row }">
          <span v-if="row.report_file_name" class="report-file">
            {{ row.report_file_name }}
          </span>
          <span v-else class="no-report">暂无报告</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="total_count" label="总任务数" width="100" />
      <el-table-column prop="success_count" label="成功数" width="100" />
      <el-table-column prop="failed_count" label="失败数" width="100" />
      
      <el-table-column prop="duration" label="执行时长" width="120">
        <template #default="{ row }">
          {{ formatDuration(row.duration) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.created_at) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            size="small" 
            @click="viewDetail(row)"
          >
            详情
          </el-button>
          
          <el-button 
            v-if="row.report_file_name"
            type="primary" 
            size="small" 
            @click="viewReport(row)"
          >
            查看报告
          </el-button>
          
          <el-button 
            v-if="row.report_file_name"
            size="small" 
            @click="downloadReport(row)"
          >
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadExecutions"
        @current-change="loadExecutions"
      />
    </div>

    <!-- 执行详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="`执行详情 - ${currentExecution?.execution_name}`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="currentExecution" class="execution-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="执行文件名">
            {{ currentExecution.execution_name }}
          </el-descriptions-item>
          <el-descriptions-item label="脚本名称">
            {{ currentExecution.script_name }}
          </el-descriptions-item>
          <el-descriptions-item label="执行类型">
            <el-tag :type="currentExecution.execution_type === 'batch' ? 'warning' : 'info'">
              {{ currentExecution.execution_type === 'batch' ? '批量执行' : '单个执行' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentExecution.status)">
              {{ getStatusText(currentExecution.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行时长">
            {{ formatDuration(currentExecution.duration) }}
          </el-descriptions-item>
          <el-descriptions-item label="任务统计">
            总数: {{ currentExecution.total_count }}, 
            成功: {{ currentExecution.success_count }}, 
            失败: {{ currentExecution.failed_count }}
          </el-descriptions-item>
          <el-descriptions-item label="报告文件">
            {{ currentExecution.report_file_name || '暂无报告' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(currentExecution.created_at) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 错误信息 -->
        <div v-if="currentExecution.error_message" class="error-section">
          <h4>错误信息</h4>
          <el-alert
            :title="currentExecution.error_message"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
        
        <!-- 执行日志 -->
        <div v-if="currentExecution.execution_logs" class="logs-section">
          <h4>执行日志</h4>
          <div class="logs-container">
            <pre>{{ currentExecution.execution_logs }}</pre>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button 
          v-if="currentExecution?.report_file_name"
          type="primary" 
          @click="viewReport(currentExecution)"
        >
          查看报告
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getUiAutomationExecutions, viewUiAutomationReport, downloadUiAutomationReport } from '../../api/uiAutomation'

// 响应式数据
const loading = ref(false)
const executions = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const filterStatus = ref('')
const filterType = ref('')

// 详情对话框
const detailVisible = ref(false)
const currentExecution = ref(null)

// 加载执行记录
const loadExecutions = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    if (filterStatus.value) {
      params.status = filterStatus.value
    }
    
    if (filterType.value) {
      params.execution_type = filterType.value
    }
    
    const response = await getUiAutomationExecutions(params)
    if (response.data.success) {
      executions.value = response.data.data.items
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('加载执行记录失败:', error)
    ElMessage.error('加载执行记录失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const viewDetail = (execution) => {
  currentExecution.value = execution
  detailVisible.value = true
}

// 查看报告
const viewReport = (execution) => {
  if (!execution.report_file_name) {
    ElMessage.warning('该执行记录暂无报告文件')
    return
  }
  
  const reportUrl = viewUiAutomationReport(execution.report_file_name)
  window.open(reportUrl, '_blank')
}

// 下载报告
const downloadReport = (execution) => {
  if (!execution.report_file_name) {
    ElMessage.warning('该执行记录暂无报告文件')
    return
  }
  
  const downloadUrl = downloadUiAutomationReport(execution.report_file_name)
  const link = document.createElement('a')
  link.href = downloadUrl
  link.download = execution.report_file_name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 状态相关方法
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    running: 'warning',
    success: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待执行',
    running: '执行中',
    success: '成功',
    failed: '失败',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

// 格式化时长
const formatDuration = (duration) => {
  if (!duration) return '--'
  if (duration < 60) return `${duration}秒`
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}分${seconds}秒`
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '--'
  return new Date(time).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadExecutions()
})
</script>

<style scoped>
.execution-reports-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.search-filters {
  display: flex;
  gap: 12px;
  align-items: center;
}

.el-table {
  flex: 1;
}

.pagination {
  padding: 16px;
  display: flex;
  justify-content: center;
}

.report-file {
  color: #409eff;
  font-size: 12px;
}

.no-report {
  color: #909399;
  font-size: 12px;
}

.execution-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.error-section {
  margin-top: 20px;
}

.error-section h4 {
  margin-bottom: 10px;
  color: #f56c6c;
}

.logs-section {
  margin-top: 20px;
}

.logs-section h4 {
  margin-bottom: 10px;
  color: #606266;
}

.logs-container {
  max-height: 300px;
  overflow-y: auto;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
}

.logs-container pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', Consolas, monospace;
  font-size: 12px;
  line-height: 1.4;
}
</style>
